#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from event import event_type
from command import command
import logging
from utility import tools
from datetime import datetime, timedelta
from utility import his_api
from command.handler import dict_handler

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


class HospitalizedPatientRecListAPI(Resource):
    """
    住院医生工作站 左侧住院人列表
    :request: post
    :param status: 状态 NULL 全部 1 在院 2 出院
    :param searchText: 查询字符串 姓名或者床号
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            his_ = his_api.APIHis()
            records_list = his_.get_zybasicInfo(params.get('status'))
            data_ = {'dataList':[]}
            if records_list:
                for record_ in records_list:
                    #返回结果处理 模糊搜索
                    record_tmp = {
                                'bedCode': record_['name'],
                                'name': record_['name'],
                                'archivesId': '',
                                'hljb': record_['name'],
                                'zyh': record_['name']
                    } 
                    #添加开关
                    is_add = False
                    if params.get('searchText'):
                        search_text = params.get('searchText')
                        if search_text in record_['name'] or search_text in record_['name']:
                             is_add = True
                    else:
                        is_add = True
                    if  is_add:
                        #  更新档案信息
                        query_ = [('mq_sfz', '=', params.get('cardNo'))]
                        res_archive = odoo.env['res.archives'].search_read(query_,['id'])
                        if res_archive:
                            res_archive = res_archive[0]
                            record_tmp['archivesId'] = res_archive['id']   
                        data_['dataList'].append(record_tmp)    
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class MedicalRecListAPI(Resource):
    """
    右侧获取病历管理列表
    :request: get
    :param archivesId: 档案ID
    :returns: json string
    """
    def get(self):
        try:
            odoo = OdooManager().get_instance()
            params = request.values
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            data_ = {'dataList':[]}   
            query_ = [
                ('type', '=', '1')
            ]
            title = ''
            type_ = '分娩记录'

            fm_set = {
                "birth.record": 0,
                "birth.uterus.record": 1,
                "birth.baby.record": 2
            }
            #  查询病例配置表
            res_config_case = odoo.env['res.config.case'].search_read(query_)
            if res_config_case:
                for config_item in res_config_case:
                    data_item = {
                        "title": config_item['title'],
                        "id": None,
                        "type": int(config_item['type']) - 1,
                        "detailType": fm_set[config_item['url']],
                        "status": 0,
                    }
                    detail_data = odoo.env[config_item['url']].search_read([(
                        'archives_id', '=', int(params.get('archivesId'))
                    )])
                    if detail_data:
                        detail_data = detail_data.pop()
                        data_item['id'] = detail_data['id']
                        data_item['status'] = 1
                        data_item['ysName'] = detail_data['create_uid'][1] if detail_data['create_uid'] else None
                        data_item['jgName'] = detail_data['hospital_id'][1] if detail_data['hospital_id'] else None
                        data_item['updateDate'] = detail_data['write_date']
                    data_['dataList'].append(data_item)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

